﻿using System;
using System.Linq;
using System.Collections.Generic;

using Spencen.Mobile.UI;
using Spencen.Mobile.UI.Controls;
using Spencen.Mobile.UI.Navigation;
using Spencen.Mobile.UI.Commanding;
using Spencen.Mobile.Markup;

using Commute.Model;

namespace Commute.Presenters
{
    public class TimetablePresenter
    {
        private IDrawingHost _host;
        private INavigator _navigator;

        public TimetablePresenter( INavigator navigator )
        {
            LoadModel();

            RouteCommand = new DelegateCommand( Route );
            _navigator = navigator;
        }

        public DelegateCommand RouteCommand { get; private set; }
        public Timetable Timetable { get; private set; }

        public View CreateView( IDrawingHost host )
        {
            _host = host;

            // XAML Loading
            var text = (System.IO.Stream)System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream( "Commute.Views.TimetableView.xml" );
            var xamlRenderer = new XamlRenderer( _host, this );
            var view = (View)xamlRenderer.Render( text );

            return view;
        }

        private void Route()
        {
            var presenter = new RoutePresenter( _navigator );
            presenter.Initialize( Timetable );
            _navigator.Forward( presenter.CreateView( _host ) );
        }

        private void LoadModel()
        {
            var modelLoader = new ModelLoader();
            string executingPath = System.Reflection.Assembly.GetCallingAssembly().GetName().CodeBase;
            string fullPath = System.IO.Path.Combine( executingPath.Substring( 0, executingPath.LastIndexOf( "\\" ) ), "BusService.xml" );

            Timetable = modelLoader.LoadTimetable( fullPath );
        }
    }
}
